<template>
	<view>
		<view :style="{height: titleNavHeight + statusBarHeight + 5 + 'px'}" style="position: fixed;top: 0;left: 0;right: 0;z-index: 9999;background-color: #ffffff;
			border-bottom: 1px solid #ebedf0;">
			<view :style="{height: titleNavHeight + 'px', top: statusBarHeight + 'px', width: '100%'}" class="nav-bar">
				<text class="text">工作台</text>
			</view>
		</view>
		<view :style="{height: titleNavHeight + statusBarHeight + 5 + 'px'}"></view>
		<view style="padding: 16px 16px 10px 16px">
			<u-swiper :list="bannerList" mode="round"
			@click="onEntryItemClick(item.entryId, item.extraData)"></u-swiper>
			<!-- <p class="commons-title">{{ group.entryName }}</p> -->

			<view class="commons" v-for="group in commonList" :key="group.entryId">
				<u-grid class="commons-ctn" :col="4" :border="false">
					<u-grid-item class="commons-ctn-item" v-for="(item,index) in group.children" :index="index"
						:key="item.entryId" @click="onEntryItemClick(item.entryId, item.extraData)">
						<view class="commons-ctn-item-icon">
							<u-image width="44px" height="44px" :src="item.imageData || homeGridIcon2x"></u-image>
						</view>
						<view class="commons-ctn-item-text">{{item.entryName}}</view>
					</u-grid-item>
				</u-grid>
			</view>

			
			
	<!-- 宫格组件 -->
	<!-- <view class="grid-body" v-for="group in commonList" :key="group.entryId">
			<uni-grid :column="2" :showBorder="false">
				<uni-grid-item v-for="(item,index) in group.children" :index="index" style="height: 140px;">
					<view class="grid-item-box" @click="onEntryItemClick(item.entryId, item.extraData)">
						<image :src="item.imageData" style="width:100%;height: 100%;border-radius: 6px;background-color: white;" />
						<text class="title">{{ item.entryName }}</text>
						<text class="text">{{ item.entryName }}</text>
					</view>
				</uni-grid-item>
			</uni-grid>
		</view> -->
			
			<!-- <view class="cell" v-for="(item,index) in taskCellList" :key="index">
				<u-cell-group :border="false" style="width: 100%;">
					<u-cell-item :arrow="true" :title="item.title" :border-bottom="false" :center="true"
						:title-style="titleStyle" @click="goTaskList(index)">
						<template v-slot:right-icon v-if="index == 0">
							<u-badge type="error" :count="item.value" :absolute="false" size="default"></u-badge>
						</template>
					</u-cell-item>
				</u-cell-group>
			</view> -->

			<view>
				<u-toast ref="uToast" />
			</view>
		</view>
	</view>
</template>

<script>
	import Vue from 'vue';
	import pageConfig from '@/pages.json';
	import {
		getBoundingClientRect
	} from "@/utils";
	import {
		treeDataTranslate,
		setObjectToSessionStorage
	} from '@/utils';
	import {
		uploadMixin
	} from '@/core/mixins';
	import {
		FlowOperationController
	} from '@/api/flowController.js';
	import {
		StudentSignInController,
		SystemController
	} from "@/api/index.js"

	export default {
		mixins: [uploadMixin],
		data() {
			const {
				windowWidth,
				statusBarHeight
			} = uni.getSystemInfoSync()
			const rect = getBoundingClientRect(windowWidth, statusBarHeight)
			return {
				windowWidth: windowWidth,
				statusBarHeight: statusBarHeight,
				titleNavHeight: (rect.top - statusBarHeight) * 2 + rect.height,
				emptyWidth: rect.left - 10,
				headerHeight: 0,
				homeGridIcon2x: require('../../static/home/homeGridIcon2x.png'),
				swiperImg: require('../../static/home/swiperImg.png'),
				getHomeEntryList: [],
				titleStyle: {
					'color': '#333333',
					'font-weight': 'bold',
					'font-size': '32rpx'
				},
				taskCellList: [{
						title: '待办任务',
						value: '10'
					},
					{
						title: '历史任务',
						value: '100'
					},
					{
						title: '已办任务',
						value: '9'
					}
				],
				routerMap: {}
			}
		},
		// created() {
		// 	this.getHomeEntryList = uni.getStorageSync('setHomeEntryList')
		// 	console.log(this.getHomeEntryList)
		// },
		mounted() {
			this.getHomeEntryList = uni.getStorageSync('setHomeEntryList');
			this.buildPageConfig();
			this.formInit();
			this.checkForUpdate();

		},
		methods: {
			async checkForUpdate() {
				let obj = {
					apkVersionDtoFilter: {
						status: 1
					}
			
				}
				let res = await SystemController.getApkVersionList(this, obj);
				let Response = res.dataList[0]
				//获取当前安装包版本号
				const currentVersionCode = await this.getCurrentVersionCode();
				// console.log("当前版本号:", currentVersionCode);
				// console.log("最新版本号:", Response);
				// 对比版本号
				if (Response.latestPersionCode > currentVersionCode) {
					// 显示更新对话框
					// appDialog.show(Response.path, Response.changelog);
					uni.showTabBarRedDot({
						index: 2
					})
				} else {
					uni.hideTabBarRedDot({
						index:2
					})
					// uni.showToast({
					// 	title: '当前已是最新版',
					// 	icon: 'none'
					// });
				}
			},
			getCurrentVersionCode() {
				return new Promise((resolve) => {
					//获取当前安装包版本号
					plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
						resolve(parseInt(wgtinfo.versionCode));
					});
				});
			},
			buildPageConfig() {
				this.routerMap = {};
				if (pageConfig) {
					if (Array.isArray(pageConfig.pages)) {
						pageConfig.pages.forEach(page => {
							if (page.name && page.name !== '') {
								let path = '/' + page.path;
								this.routerMap[page.name] = path;
							}
						});
					}
					if (Array.isArray(pageConfig.subPackages)) {
						pageConfig.subPackages.forEach(subPackage => {
							let root = subPackage.root;
							if (Array.isArray(subPackage.pages)) {
								subPackage.pages.forEach(page => {
									if (page.name && page.name !== '') {
										let path = '/' + root + '/' + page.path;
										this.routerMap[page.name] = path;
									}
								});
							}
						});
					}
				}
			},
			swiperClick(index) {},
			onEntryItemClick(entryId, extraObject) {
				if (JSON.parse(extraObject).formRouterName == "signIn") {
					this.sansQrCodes();
				} else {
					this.jumpTo(entryId, extraObject);
				}

			},
			sansQrCodeCallback(data) {
				console.log(data)
				let studentSignInDto={
					classId:JSON.parse(data.getData).classId,
					teacherId:JSON.parse(data.getData).teacherId,
					courseId:JSON.parse(data.getData).courseId,
					longitude:data.longitude,
					latitude:data.latitude,
					expirationTime:JSON.parse(data.getData).expirationTime
				}
				
				StudentSignInController.signin(this,{studentSignInDto:studentSignInDto}).then((res) => {
					console.log("res", res)
					if (res) {
						this.showSuccess()
					} else {
						this.showError()
					}
				}).catch((err) => {
					console.error(err);
				})
			},
			sansQrCodes() {
				// this.checkOpenGPSService();
				this.getLongitudeAndLatitude();
				let that = this;
				// 只允许通过相机扫码
				uni.scanCode({
					scanType: ['qrCode'],
					onlyFromCamerLa: true,
					success: function(res) {
						var prop = {}
					
						prop.getData = res.result;
						prop.address = that.address;
						prop.longitude = that.longitude;
						prop.latitude = that.latitude;
						that.sansQrCodeCallback(prop)
					}
				});

			},
			async getLongitudeAndLatitude() {
				let that = this;
				await uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						console.log(res)
						that.longitude = res.longitude;
						that.latitude = res.latitude;
						console.log(that.longitude)
						console.log(that.latitude)
					}
				})
			},
			showSuccess() {
				this.$refs.uToast.show({
					title: '签到成功',
					type: 'success'
				})
			},

			showError() {
				this.$refs.uToast.show({
					title: '签到失败',
					type: 'error'
				})
			},
			jumpTo(entryId, menu) {
				const menuItem = JSON.parse(menu)
				if (menuItem != null && setObjectToSessionStorage('currentMenuId', entryId)) {
					// 路由表单
					if (menuItem.bindType === this.SysMenuBindType.ROUTER && menuItem.formRouterName) {
						let path = this.routerMap[menuItem.formRouterName];
						if (path != null && path !== '') {
							uni.navigateTo({
								url: path
							});
						} else {
							console.error('未找到路由：' + menuItem.formRouterName);
						}
						return
					}
					// 在线表单菜单
					if (menuItem.bindType === this.SysMenuBindType.ONLINE_FORM && menuItem.onlineFormId != null && menuItem
						.onlineFormId !== '') {
						uni.navigateTo({
							url: '/views/online/form?passData=' + encodeURIComponent(JSON
								.stringify({
									formId: menuItem.onlineFormId,
									formType: this.SysOnlineFormType.QUERY
								}))
						})
					}
					// 工单列表菜单
					if (menuItem.bindType === this.SysMenuBindType.WORK_ORDER &&
						menuItem.onlineFormId != null && menuItem.onlineFormId !== '' &&
						menuItem.onlineFlowEntryId != null && menuItem.onlineFlowEntryId !== '') {
						uni.navigateTo({
							url: '/views/online/form?passData=' + encodeURIComponent(JSON
								.stringify({
									formId: menuItem.onlineFormId,
									entryId: menuItem.onlineFlowEntryId
								}))
						})
					}
					// 报表菜单
					if (menuItem.bindType === this.SysMenuBindType.REPORT && menuItem.reportPageId != null && menuItem
						.reportPageId !== '') {
						uni.navigateTo({
							url: '/views/report/index?pageId=' + menuItem.reportPageId
						})
					}
				}
			},
			goTaskList(index) {
				if (index === 0) {
					uni.navigateTo({
						url: '/views/workflow/formRuntimeTask/formMyTask'
					})
				} else if (index === 1) {
					uni.navigateTo({
						url: '/views/workflow/formRuntimeTask/formMyHistoryTask'
					})
				} else if (index === 2) {
					uni.navigateTo({
						url: '/views/workflow/formRuntimeTask/formMyApprovedTask'
					})
				}
			},
			formInit() {
				let params = {
					pageParam: {
						pageNum: 1,
						pageSize: 1
					},
				}
				FlowOperationController.countRuntimeTask(this).then(res => {
					// 代办任务
					this.taskCellList[0].value = res || 0;
				}).catch(e => {});
			}
		},
		computed: {
			getFinalEntryList() {
				return (this.getHomeEntryList || []).map(item => {
					let temp = {
						...item
					}
					try {
						temp.imageData = temp.imageData ? JSON.parse(temp.imageData) : undefined;
						if (temp.imageData) {
							temp.imageData = this.getUploadFileUrl(temp.imageData, {
								filename: temp.imageData.filename
							})
						}
					} catch (e) {
						temp.imageData = null;
					}
					return temp;
				});
			},
			commonList() {
				if (Array.isArray(this.getFinalEntryList)) {
					let tempList = this.getFinalEntryList.filter(item => {
						return item.entryType === this.MobileEntryType.GROUP || item.entryType === this
							.MobileEntryType.SUDOKU;
					});
					if (Array.isArray(tempList)) {
						return treeDataTranslate(tempList.map(item => {
							return {
								...item
							}
						}), 'entryId', 'parentId').filter(item => (item.children || []).length > 0);
					}
				}

				return [];
			},
			bannerList() {
				if (Array.isArray(this.getFinalEntryList)) {
					let arr = this.getFinalEntryList.filter(item => {
						return item.entryType === this.MobileEntryType.BANNER;
					});
					let bannerlist = arr.map(item => {
						return {
							...item,
							image: item.imageData || this.swiperImg
						}
					})
					return bannerlist
				} else {
					return [];
				}
			},
		}
	}
</script>

<style lang="less" scoped>
	.nav-bar {
		position: absolute;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding-left: 20rpx;

		.text {
			max-width: 60%;
			margin: 0 auto;
			color: #323233;
			font-weight: 500;
			font-size: 30rpx;
		}

		.nav-right {
			display: flex;

			.mobile-font {
				color: #707070;
				font-size: 36rpx;

				&+.mobile-font {
					margin-left: 12rpx;
				}
			}
		}
	}

	.commons {
		width: 100%;
		// height: 13rem;
		// overflow: auto;
		margin-top: 32rpx;
		// border-radius: 16rpx;
		// padding: 24rpx 0;
		background: #ffffff;
	}

	.commons-title {
		margin: 0;
		padding: 24rpx 30rpx;
		color: #000000;
		font-weight: 700;
		font-size: 32rpx;
	}

	.commons-ctn-item {
		// margin-bottom: 20rpx;
		// border-radius: 16rpx;
	}

	.commons-ctn-item-icon {
		width: 88rpx;
		height: 88rpx;
		margin-bottom: 6rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 16rpx;
	}

	.commons-ctn-item-text {
		width: 100%;
		font-size: 24rpx;
		color: #646566;
		text-align: center;
		margin-top: 16rpx;
	}

	// .cell {
	// 	width: 100%;
	// 	height: 112rpx;
	// 	background-color: #ffffff;
	// 	border-radius: 16rpx;
	// 	margin: 32rpx 0;
	// 	display: flex;
	// 	align-items: center;
	// }
	// .text {
	// 	text-align: center;
	// 	margin-left: 4px;
	// 	font-size: 12px;
	// 	margin-top: 8rpx;
	// }

	// .title {
	// 	position: absolute;
	// 	width: 40px;
	// 	height: 40px;
	// 	font-size: 15px;
	// 	font-weight: 500;
	// 	letter-spacing: 0.2em;
	// 	margin: 36px 0 0 8px;
	// 	color: white;
	// }

	// .grid-item-box {
	// 	flex: 1;
	// 	display: flex;
	// 	flex-direction: column;
	// 	align-items: flex-start;
	// 	justify-content: center;
	// 	margin: 15px 12px 0 10px;
	// }
</style>
<style>
	.u-cell {
		padding: 20rpx 32rpx !important;
	}

	.uicon-arrow-right {
		color: #969799;
	}
</style>